<template>
    <div class="load">
        <div class="top">
            <div class="left">
                <div class="item">
                    <div class="label">
                        <span></span>
                        <span>卸船船期</span>
                    </div>
                    <el-select v-model="condition.scdId" placeholder="请选择" clearable filterable size="small"
                        style="width:250px" @change="changeScdId">
                        <el-option v-for="item in scdTypeList" :key="item.id"
                            :label="item.termCode + '/' + item.vesselName+'/'+item.ivoyage+'/'+item.evoyage"
                            :value="item.id"></el-option>
                    </el-select>
                </div>
            </div>
            <div class="right">
                <span style="color: red;font-weight: bold;margin-right: 40px">{{boxCountInfo}}</span>
                <span></span>
                <el-button type="primary" class="search" :loading="btnLoading" @click="addBox">新增箱</el-button>
                <el-button type="primary" class="search" :loading="btnLoading3" @click="upload">导入</el-button>
                <el-button type="danger" class="del" @click="delAll" plain>批量删除</el-button>
                <el-button type="primary" class="search" :loading="btnLoading2"
                    @click="loadAndUploadSubmit">提交</el-button>
                <el-button type="primary" class="search" @click="checkbillStatus">状态检查</el-button>
                <el-button type="primary" class="search" :loading="btnLoading1" @click="downLoad">下载模板</el-button>
            </div>
        </div>
        <div class="table">
            <el-table :data="tableData" :header-cell-style="{ background: '#EEF1F5'}" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50">
                </el-table-column>
                <el-table-column prop="no" label="序号" width="50">
                </el-table-column>
                <el-table-column prop="billno" label="提单号" width="150">
                </el-table-column>
                <el-table-column prop="goodsDisplay" label="货名" width="150">
                </el-table-column>
                <el-table-column prop="cntrno" label="箱号" width="150">
                </el-table-column>
                <el-table-column prop="ctypecd" label="箱型" width="70">
                </el-table-column>
                <el-table-column prop="cszCsizecd" label="尺寸" width="70">
                </el-table-column>
                <el-table-column prop="cstatusName" label="空重" width="70">
                </el-table-column>
                <el-table-column prop="sealno" label="铅封号" width="100">
                </el-table-column>
                <el-table-column prop="tranship" label="中转箱" width="70">
                </el-table-column>
                <el-table-column prop="potLdportName" label="装货港" width="100">
                </el-table-column>
                <el-table-column prop="potUnldportName" label="卸货港" width="100">
                </el-table-column>
                <el-table-column prop="potDstnportName" label="目的港" width="100">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button @click="edit(scope.row,scope.$index)" type="text"
                            style="color: #737373">编辑</el-button>
                        <el-button type="text" style="color:  #737373" @click="del(scope.$index)">删除</el-button>
                        <el-button type="text" style="color: #737373"
                            @click="addGoods(scope.row,scope.$index)">货列表</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog title="" :visible.sync="dialogVisible" width="65%" :before-close="beforeCloseDialog">
            <addBox ref="addBox" :deliverOriginalData="saveOriginalData" v-if="visible=='box' && dialogVisible"
                @closeDialog="dialogVisible = false" @addItem="addItem"></addBox>
            <addGoods ref="addGoods" :deliverOriginalData="saveOriginalData" :boxInfo="boxInfo" :id="condition.scdId"
                @closeDialog="dialogVisible = false" @addItem="addItem" v-if="visible=='goods' && dialogVisible">
            </addGoods>
        </el-dialog>
        <el-dialog title="" :visible.sync="dialogVisible1" width="65%">
            <uploadExl :scdId="condition.scdId" :voyType="condition.voyType" v-if="dialogVisible1" @set="setBox">
            </uploadExl>
        </el-dialog>
    </div>
</template>

<script>
import uploadExl from '../../../components/uploadExl.vue'
import addBox from './addBox.vue'
import addGoods from './addGoods.vue'
import { boxDataCount,downloadExcelTemplate,fillDisplay } from '@/util/CommUtil'
export default {
    name: 'unloadList',
    components: { addBox, addGoods,uploadExl },
    data() {
        return {
            boxCountInfo: '',
            tableData: [],
            dataList:[],
            termList: [],
            scdTypeList: [],
            condition: {
                scdId: '',
                voyType: '',
                billno: '',
                cntrno: '',
            },
            dialogVisible: false,
            dialogVisible1:false,
            visible: 'box',
            btnLoading: false,
            btnLoading1:false,
            btnLoading2: false,
            btnLoading3: false,
            boxInfo: {},
            isChecked: false,
            currentIndex: -1,
            multipleSelection: [],
            oldJsonStr:'',//弹窗打开时保存数据
            oldFormJson:[],
            isQueryOpen:false
        }
    },
    //通过路由规则，离开该组件时被调用
    beforeRouteLeave (to, from, next) {
        let nowJsonData = JSON.stringify(this.tableData)
        let oldFormJson = JSON.stringify(this.oldFormJson)
        if(nowJsonData!=oldFormJson && this.isQueryOpen){
            this.$nextTick(()=>{
                this.$confirm('存在未提交信息，确认关闭？',{
                    closeOnHashChange:false,
                    closeOnClickModal:false,
                    distinguishCancelAndClose:true,
                    closeOnPressEscape:false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                })
                    .then(_ => {
                        this.$store.commit('setActiveMenuPath',next.fullPath)
                        next()
                    })
                    .catch(_ => {
                        this.$store.commit('setActiveMenuPath',from.fullPath)
                        this.$nextTick(()=>{
                            this.$refs.newLeftMenu2.refresh = !this.$refs.newLeftMenu2.refresh
                            this.$refs.newLeftMenu2.getPath(from.fullPath)
                            this.$refs.newLeftMenu2.linkTab(from.fullPath)
                        })
                    });
            })
        }else{
            next()
        }
    },
    methods: {
        saveOriginalData(data){
            this.oldJsonStr = data
        },
        /* 关闭对话框前提示 */
        beforeCloseDialog(done){
            let nowJsonData = ''
            if(this.visible=='box'){
                nowJsonData = this.$refs.addBox.getNowData()
            }else if(this.visible=='goods'){
                nowJsonData = this.$refs.addGoods.getNowData()
            }
            console.log('nowJsonData',nowJsonData,'oldJsonStr',this.oldJsonStr);
            if(nowJsonData != this.oldJsonStr){
                this.$confirm('存在未提交信息，确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            }else{
                done();
            }
        },
        downLoad(){
            downloadExcelTemplate('unloadlistTemplate.xls')
        },
        upload(){
            if (!this.condition.scdId) {
                this.$message.error('请先选择船期')
                return
            }
            this.dialogVisible1=true
        },
        loadAndUploadFind() {
            this.$api.loadAndUploadFind(this.condition).then((res) => {
                this.tableData = res.data
                fillDisplay(this.tableData)
                // 重新计算箱统计数量
                this.boxCountInfo = boxDataCount(this.tableData)
            })
        },
        // 检查装卸船清单下发码头状态
        checkbillStatus() {
            this.$api.findOneBeforeBill({ id: this.condition.scdId }).then((res) => {
                let voyId =
                    this.$route.name == 'loadList'
                        ? res.data.evoyageId
                        : res.data.ivoyageId
                if (!voyId) {
                    this.$message.error('不可操作')
                    return
                }
                this.$api
                    .billStatusJX({ voyId })
                    .then((res) => {
                        if (res.data && res.data.auditInfo) {
                            this.$message.error(res.data.auditInfo)
                        }else{
                            this.$message.success('装船清单下发码头状态正常')
                        }
                    }).catch((err) => {})
            }).finally(()=>{})
        },
        findSimpleSchedule() {
            this.$api.findSimpleSchedule(this.condition).then((res) => {
                this.scdTypeList = res.data
            })
        },
        addGoods(item, index) {
            this.currentIndex = index
            this.boxInfo = item
            this.dialogVisible = true
            this.visible = 'goods'
            if (item.goods) {
                this.$nextTick(() => {
                    this.$refs.addGoods.goods = [...item.goods]
                })
            }
        },
        setBox(list){
            this.tableData = list
            fillDisplay(this.tableData)
            // 重新计算箱统计数量
            this.boxCountInfo = boxDataCount(this.tableData)
        },
        addBox() {
            if (!this.condition.scdId) {
                this.$message.error('请先选择船期')
                return
            }
            if (!this.isChecked) {
                this.check()
            } else {
                this.dialogVisible = true
                this.visible = 'box'
                this.currentIndex = -1
            }
        },
        addItem(form) {
            if (this.currentIndex == -1) {
                this.tableData.push(form)
            } else {
                if (this.visible == 'box') {
                    form.goods = this.tableData[this.currentIndex].goods
                }
                if (form.goods && form.goods.length > 0) {
                    form.billno = form.goods[0].billno
                }
                this.tableData.splice(this.currentIndex, 1, form)
            }
            this.dialogVisible = false
            /* 添加数据后询问是否继续跳转 */
            this.isQueryOpen = true
        },
        edit(item, index) {
            this.currentIndex = index
            this.dialogVisible = true
            this.visible = 'box'
            this.$nextTick(() => {
                this.$refs.addBox.form = { ...item }
            })
        },
        del(index) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示')
                .then(() => {
                    this.tableData.splice(index, 1)
                })
                .catch(() => {})
        },
        delAll() {
            if (this.multipleSelection.length == 0) {
                this.$message.error('请选择数据')
                return
            }
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示')
                .then(() => {
                    this.tableData = this.tableData.filter(
                        (item) => !this.multipleSelection.includes(item)
                    )
                })
                .catch(() => {})
        },
        changeScdId(e) {
            this.isChecked = false
            this.condition.scdId = e
            if(e){
                this.loadAndUploadFind()
                this.checkOne()
            }else{
                this.tableData = []
            }
        },
        //校验
        check() {
            this.btnLoading = true
            this.$api.findOneBeforeBill({ id: this.condition.scdId }).then((res) => {
                let voyId =
                    this.$route.name == 'loadList'
                        ? res.data.evoyageId
                        : res.data.ivoyageId
                if (!voyId) {
                    this.$message.error('不可操作')
                    return
                }
                this.$api
                    .billCheckJX({ voyId })
                    .then((res) => {
                        if (res.data) {
                            this.isChecked = true
                            this.dialogVisible = true
                            this.visible = 'box'
                            this.btnLoading = false
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    })
                    .finally(() => {
                        this.btnLoading = false
                    })
            })
                .catch((err) => {
                    console.log(err);
                })
                .finally(() => {
                    this.btnLoading = false
                })
        },
        checkOne() {
            this.btnLoading = true
            this.$api.findOneBeforeBill({ id: this.condition.scdId }).then((res) => {
            }).finally(()=>{
                this.btnLoading = false
            })
        },
        //下发
        loadAndUploadSubmit() {
            if (this.tableData.length == 0) {
                this.$message.error('界面无数据，不可操作')
                return
            }
            for (let i = 0; i < this.tableData.length; i++) {
                if (!this.tableData[i].goods || this.tableData[i].goods.length == 0) {
                    this.$message.error(`第${i + 1}行数据不存在货信息，不可操作`)
                    return
                }
            }
            let params = {
                boxes: this.tableData,
                opType: 'create',
                scdId: this.condition.scdId, //航次id
                voyType: this.condition.voyType,
            }
            this.btnLoading2 = true
            this.$api
                .loadAndUploadSubmit(params)
                .then((res) => {
                    if (res.message == 'success') {
                        this.$message.success('下发成功')
                        this.isQueryOpen = false
                        this.$router.push({
                            query: {
                                name: 'shipPlanList',
                            },
                            name: 'success',
                        })
                        this.loadAndUploadFind()
                    } else {
                        this.$message.error(res.message)
                    }
                    this.btnLoading2 = false
                })
                .catch((err) => {})
        },
        handleSelectionChange(v) {
            this.multipleSelection = v
        },
    },

    computed: {},

    mounted() {
        this.condition.voyType = this.$route.name == 'unloadList' ? 'I' : 'E'
        console.log(this.condition.voyType)
        this.condition.scdId = this.$route.query.id
        this.findSimpleSchedule()
        if (this.condition.scdId) {
            this.loadAndUploadFind()
            this.checkOne()
        }
    },
}
</script>
<style lang='less' scoped>
.load {
    background: #fff;
    padding: 20px;
}

.top {
    display: flex;
    align-items: flex-start;

    border-bottom: 1px solid #d7d7d7;
    box-sizing: border-box;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000000;
    line-height: 16px;
    display: flex;

    .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 17px;

        .label {
            margin-right: 5px;
            width: 80px;

            span:first-child {
                color: #ff3838;
            }
        }
    }

    .search {
        background: #0f47b8;
        height: 30px;
        padding: 5px 10px;
    }

    .del {
        height: 30px;
        padding: 5px 10px;
    }

    .left {
        display: flex;
        flex: 1;
        flex-wrap: wrap;
    }
}

/deep/.el-dialog__footer {
    text-align: center;

    .el-button {
        color: #fff;
        background: #0f47b8;
        height: 30px;
        width: 100px;
        padding: 5px 10px;
    }
}

/deep/.el-dialog__header {
    padding: 0;
}

/deep/.el-dialog__body {
    padding: 20px;
}
</style>